﻿using System;
using UnityEngine;

public static class AnimationExtensions
{
    public static void PlayWithCallBack(this Animation ani, string clipName, Action<string> callBack)
    {
        if (callBack != null)
        {
            var aniCallBack = ani.gameObject.GetComponent<AniCallBack>();
            if (aniCallBack == null)
                ani.gameObject.AddComponent<AniCallBack>().CallBack = callBack;
            else
                aniCallBack.CallBack = callBack;

            var endEvent = new AnimationEvent
            {
                functionName = "MyAniCallBack",
                stringParameter = clipName,
                time = ani[clipName].length
            };

            var needAdd = true;
            var clip = ani.GetClip(clipName);
            for (var i = 0; i < clip.events.Length; i++)
                if (clip.events[i].time == endEvent.time)
                {
                    clip.events[i] = endEvent;
                    needAdd = false;
                }

            if (needAdd) clip.AddEvent(endEvent);
        }

        ani.Play(clipName);
    }
}